/**
 * 考试系统 v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout, {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
  DefaultFooter,
  getMenuData,
} from '@ant-design/pro-layout';
import React, { useEffect } from 'react';
import { Link, useIntl, connect, Dispatch, history } from 'umi';
import { Result, Button } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { ConnectState } from '@/models/connect';
import { getAuthorityFromRouter, isHangda, isLianxi, isLianxiSite,isBosheng,isJuan, isTuopu } from '@/utils/utils';
const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="您没有权限访问此页面"
    extra={
      <Button type="primary">
        <Link to="/user/login">去登录</Link>
      </Button>
    }
  />
);
export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
}
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
};
/**
 * use Authorized check all menu item
 */
const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] =>
  menuList.map((item) => {
    const userinfo = JSON.parse(localStorage.getItem('userinfo') || '{}');
    const subject = userinfo.subject;
    // if (!isLianxi() && item.path === '/select') {
    //   item.path = `/exam/${subject}/2`
    // }
    if (item.path === '/select'&&((location.host==='tzsbpx.shejiyuan.com'&&!isLianxi())||location.host==='binhaipx.shejiyuan.com')) {
      item.path = `/exam/${subject}/2`
    }
    const localItem = {
      ...item,
      children: item.children ? menuDataRender(item.children) : undefined,
    };
    return Authorized.check(item.authority, localItem, null) as MenuDataItem;
  });

const defaultFooterDom = (
  <DefaultFooter
    copyright={`${new Date().getFullYear()} 特种设备作业人员在线培训学习系统 SYSTEM All Rights Reserved 备案号:鲁ICP备14014132号`}
    links={[

    ]}
  />
);

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const {
    dispatch,
    children,
    settings,
    location = {
      pathname: '/',
    },
  } = props;

  /**
   * constructor
   */

  useEffect((props: any) => {
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
    }
    if (localStorage.getItem('antd-pro-authority') === `["guest"]`) {
      history.push('/user/login')
    }
  }, []);
  /**
   * init variables
   */

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  }; // get children authority
  const routes = props.route.routes || []
  const authorized = getAuthorityFromRouter(routes, location.pathname || '/') || {
    authority: undefined,
  };
  const host = window.location.host;
  if (host === 'tzsbpx.shejiyuan.com') {
    for (let i = 0; i < routes.length; i++) {
      const item = routes[i];
      if (item.path === '/train') {
        routes?.splice(i, 1)
      }
    }
  }
  const { formatMessage } = useIntl();

  const title = () => {
    if (isTuopu()) return '安全培训系统'
    if (isJuan()) return '三项岗位人员在线培训平台'
    if (isHangda()) return '青岛航达职业技能培训学校在线培训学习系统'
    if (isBosheng()) return '特种设备三项岗位人员在线学习平台'

    if (isLianxiSite()) return '特种作业人员培训系统'
    return '在线培训学习系统'
  }
  return (
    <ProLayout
      formatMessage={formatMessage}
      onCollapse={handleMenuCollapse}
      onMenuHeaderClick={() => history.push('/')}
      menuItemRender={(menuItemProps, defaultDom) => {
        // console.log(defaultDom.props.children[1].props.children)
        if (menuItemProps.isUrl || !menuItemProps.path) {
          return defaultDom;
        }
        return <Link to={menuItemProps.path}>{defaultDom}</Link>;
      }}
      breadcrumbRender={(routers = []) => [
        {
          path: '/',
          breadcrumbName: formatMessage({ id: 'menu.home' }),
        },
        ...routers,
      ]}
      itemRender={(route, params, routes, paths) => {
        const first = routes.indexOf(route) === 0;
        return first ? (
          <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        ) : (
            <span>{route.breadcrumbName}</span>
          );
      }}
      footerRender={() => defaultFooterDom}
      menuDataRender={menuDataRender}
      rightContentRender={() => <RightContent />}
      title={title()}
      fixSiderbar
      fixedHeader
      {...props}
      // {...settings}
      logo={<img style={{ display: 'none' }} src='https://peixun.shejiyuan.com/favicon.ico' alt=" " />}
    >
      <Authorized authority={authorized!.authority} noMatch={noMatch}>
        {children}
      </Authorized>
    </ProLayout>
  );
};

export default connect(({ global, settings }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
}))(BasicLayout);
